<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <div class="logo-wrapper">
          <i class="fa fa-play-circle login-icon"></i>
        </div>
        <h2>YT工单管理系统</h2>
        <p class="subtitle">请登录您的账户</p>
      </div>

      <form @submit.prevent="handleLogin" class="login-form">
        <FormInput
          id="username"
          v-model="loginForm.username"
          label="用户名"
          icon="fa-user"
          type="text"
          placeholder="请输入用户名"
          :required="true"
        />

        <FormInput
          id="password"
          v-model="loginForm.password"
          label="密码"
          icon="fa-lock"
          type="password"
          placeholder="请输入密码"
          :required="true"
        />

        <div class="form-options">
          <label class="checkbox-container">
            <input
              type="checkbox"
              v-model="loginForm.rememberMe"
              class="checkbox-input"
            >
            <span class="checkmark"></span>
            记住我
          </label>
          <a href="#" class="forgot-link">忘记密码？</a>
        </div>

        <FormButton
          :loading="loading"
          loading-text="登录中..."
          button-class="login-button"
        >
          登录
        </FormButton>

        <div v-if="error" class="error-message">
          <i class="fa fa-exclamation-circle"></i>
          {{ error }}
        </div>
      </form>

      <div class="login-footer">
        <div class="test-accounts">
          <h3>测试账户：</h3>
          <ul>
            <li><strong>管理员:</strong> admin / admin123</li>
            <li><strong>客户:</strong> client / client123</li>
            <li><strong>员工:</strong> staff / staff123</li>
          </ul>
        </div>
        <p class="register-prompt">还没有账户？<router-link to="/register" class="register-link">立即注册</router-link></p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import FormInput from '../../components/FormInput.vue'
import FormButton from '../../components/FormButton.vue'

// 表单数据
const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

// 状态管理
const loading = ref(false)
const error = ref('')
const router = useRouter()

// 页面加载时检查是否记住用户名
onMounted(() => {
  const rememberedUsername = localStorage.getItem('rememberedUsername');
  if (rememberedUsername) {
    loginForm.username = rememberedUsername;
    loginForm.rememberMe = true;
  }
})

// 登录处理函数
// 首先尝试调用后端API进行登录认证，如果失败则回退到模拟登录
const handleLogin = async () => {
  // 重置错误信息
  error.value = ''
  
  // 简单验证 - 检查用户名和密码是否为空
  if (!loginForm.username || !loginForm.password) {
    error.value = '请输入用户名和密码'
    return
  }
  
  // 显示加载状态
  loading.value = true
  
  try {
    // 实际调用后端API进行登录认证
    // 发送POST请求到/api/auth/login接口
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams({
        username: loginForm.username,
        password: loginForm.password
      })
    });
    
    // 解析响应结果
    const result = await response.json();
    
    // 检查登录是否成功（code为0表示成功）
    if (result.code === 0) {
      // 登录成功
      const { token, role, username } = result.data;
      
      // 将认证信息保存到localStorage中
      // token用于后续请求的身份验证
      // role用于页面权限控制
      // username用于显示用户信息
      localStorage.setItem('userToken', token);
      localStorage.setItem('userRole', role);
      localStorage.setItem('username', username);
      
      // 如果用户选择了"记住我"选项，则保存用户名
      // 否则清除已保存的用户名
      if (loginForm.rememberMe) {
        localStorage.setItem('rememberedUsername', loginForm.username);
      } else {
        localStorage.removeItem('rememberedUsername');
      }
      
      // 根据用户角色跳转到相应的主页
      if (role === 'admin') {
        await router.push('/admin')
      } else if (role === 'client') {
        await router.push('/client')
      } else if (role === 'staff') {
        await router.push('/staff')
      } else {
        await router.push('/')
      }
    } else {
      // 登录失败，显示错误信息
      error.value = result.msg || '登录失败';
    }
  } catch (err) {
    // API调用失败（如网络错误或后端服务不可用）
    console.error('Login API error:', err);
    // 回退到模拟登录机制
    fallbackToMockLogin();
  } finally {
    // 重置加载状态
    loading.value = false
  }
}

// 回退到模拟登录机制
// 当后端认证服务不可用时，使用硬编码的测试账户进行登录
const fallbackToMockLogin = () => {
  // 模拟API调用延迟，提供更真实的用户体验
  setTimeout(() => {
    // 简单的模拟登录验证（实际项目中应该调用后端API）
    let token = null;
    let role = null;
    let redirectPath = '/';
    
    // 验证测试账户凭据
    if (loginForm.username === 'admin' && loginForm.password === 'admin123') {
      // 管理员登录
      token = 'admin_token_12345';
      role = 'admin';
      redirectPath = '/admin';
    } else if (loginForm.username === 'client' && loginForm.password === 'client123') {
      // 客户登录
      token = 'client_token_12345';
      role = 'client';
      redirectPath = '/client';
    } else if (loginForm.username === 'staff' && loginForm.password === 'staff123') {
      // 员工登录
      token = 'staff_token_12345';
      role = 'staff';
      redirectPath = '/staff';
    } else {
      // 登录失败，显示错误信息
      error.value = '用户名或密码错误'
      return;
    }
    
    // 保存认证信息到localStorage中
    localStorage.setItem('userToken', token);
    localStorage.setItem('userRole', role);
    localStorage.setItem('username', loginForm.username);
    
    // 如果用户选择了"记住我"选项，则保存用户名
    if (loginForm.rememberMe) {
      localStorage.setItem('rememberedUsername', loginForm.username);
    } else {
      localStorage.removeItem('rememberedUsername');
    }
    
    // 登录成功，跳转到相应页面
    router.push(redirectPath);
  }, 1000);
}
</script>

<style scoped>
/* 登录页面样式 */

.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 1rem;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.login-box {
  background: white;
  border-radius: 16px;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  width: 100%;
  max-width: 420px;
  padding: 2.5rem;
  position: relative;
  overflow: hidden;
}

.login-box::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6px;
  background: linear-gradient(90deg, #667eea, #764ba2);
}

.login-header {
  text-align: center;
  margin-bottom: 2rem;
}

.logo-wrapper {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 50%;
  margin-bottom: 1.5rem;
}

.login-icon {
  font-size: 2.5rem;
  color: white;
}

.login-header h2 {
  font-size: 1.75rem;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 0.5rem;
  letter-spacing: -0.025em;
}

.subtitle {
  color: #6b7280;
  font-size: 1rem;
  font-weight: 400;
}

.login-form {
  margin-bottom: 1.5rem;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  font-size: 0.875rem;
}

.checkbox-container {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #6b7280;
  position: relative;
  padding-left: 25px;
  user-select: none;
}

.checkbox-input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkmark {
  position: absolute;
  left: 0;
  height: 18px;
  width: 18px;
  background-color: #f3f4f6;
  border-radius: 4px;
  border: 1px solid #d1d5db;
  transition: all 0.2s ease;
}

.checkbox-container:hover .checkmark {
  background-color: #e5e7eb;
}

.checkbox-input:checked ~ .checkmark {
  background-color: #4f46e5;
  border-color: #4f46e5;
}

.checkmark::after {
  content: "";
  position: absolute;
  display: none;
}

.checkbox-input:checked ~ .checkmark::after {
  display: block;
}

.checkbox-container .checkmark::after {
  left: 6px;
  top: 2px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.forgot-link {
  color: #4f46e5;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.2s;
}

.forgot-link:hover {
  color: #4338ca;
  text-decoration: underline;
}

.login-button {
  width: 100%;
  padding: 1rem;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 1rem;
  box-shadow: 0 4px 6px rgba(79, 70, 229, 0.1);
}

.login-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(79, 70, 229, 0.2);
}

.login-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.error-message {
  margin-top: 1rem;
  padding: 1rem;
  background-color: #fef2f2;
  color: #ef4444;
  border-radius: 8px;
  font-size: 0.875rem;
  text-align: center;
  border: 1px solid #fecaca;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.login-footer {
  text-align: center;
  font-size: 0.875rem;
  color: #6b7280;
  padding-top: 1.5rem;
  border-top: 1px solid #e5e7eb;
}

.test-accounts {
  background-color: #f9fafb;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1.5rem;
  text-align: left;
}

.test-accounts h3 {
  margin-top: 0;
  margin-bottom: 0.75rem;
  color: #4b5563;
  font-size: 1rem;
  font-weight: 600;
}

.test-accounts ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.test-accounts li {
  margin-bottom: 0.5rem;
  font-size: 0.875rem;
  color: #6b7280;
}

.test-accounts li:last-child {
  margin-bottom: 0;
}

.test-accounts strong {
  font-weight: 600;
  color: #4b5563;
}

.register-prompt {
  margin: 0;
}

.register-link {
  color: #4f46e5;
  text-decoration: none;
  font-weight: 600;
  transition: color 0.2s;
}

.register-link:hover {
  color: #4338ca;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-box {
    padding: 1.75rem;
  }

  .login-header h2 {
    font-size: 1.5rem;
  }
  
  .logo-wrapper {
    width: 70px;
    height: 70px;
  }
  
  .login-icon {
    font-size: 2rem;
  }
}

@media (max-width: 360px) {
  .login-box {
    padding: 1.5rem;
  }
  
  .form-options {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
}
</style>